package me.eae.urls.idGenerator;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

/**
 * @ClassName Util
 * @Auther: tzq
 * @Date: 2021/1/14 15:08
 * @Description:
 */
public class Util {

    private static Path filePath;
    static {
        init();
        filePath = Paths.get("db", "mysql.db");
    }
    public static void init() {
        // 创建根目录
        try {
            if (!Files.exists(Paths.get("db"))) {
                Files.createDirectory(Paths.get("db"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static List<String> readFileDB() {
        List<String> dbs = new ArrayList<>();
        try (Stream<String> lines = Files.lines(filePath)) {
            lines.forEach((x) -> dbs.add(x));
        } catch (IOException e) {
            e.printStackTrace();//只是测试用例，生产环境下不要这样做异常处理
        }
        return dbs;
    }

    public static boolean writeFileDB(String value) {
        boolean isWrite = true;
        if(!Files.exists(filePath)) {
            try {
                Files.createFile(filePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try (BufferedWriter writer =
                     Files.newBufferedWriter(filePath,
                             StandardCharsets.UTF_8,
                             StandardOpenOption.APPEND)) {
            writer.write(value);
            writer.newLine();
        } catch (IOException e) {
            e.printStackTrace();
            isWrite = false;
        }
        return isWrite;
    }
}
